/*
 * Copyright (c) MuleSoft, Inc.  All rights reserved.  http://www.mulesoft.com
 * The software in this package is published under the terms of the CPAL v1.0
 * license, a copy of which has been included with this distribution in the
 * LICENSE.txt file.
 */

package org.mule.extension.db.internal.domain.statement;

import static java.sql.ResultSet.TYPE_FORWARD_ONLY;
import static java.sql.ResultSet.TYPE_SCROLL_INSENSITIVE;
import static java.sql.ResultSet.TYPE_SCROLL_SENSITIVE;
import static org.mule.extension.db.internal.domain.query.QueryType.STORE_PROCEDURE_CALL;
import static org.mule.runtime.api.util.Preconditions.checkArgument;
import org.mule.extension.db.internal.domain.autogeneratedkey.AutoGenerateKeysStrategy;
import org.mule.extension.db.internal.domain.autogeneratedkey.NoAutoGenerateKeysStrategy;
import org.mule.extension.db.internal.domain.connection.DbConnection;
import org.mule.extension.db.internal.domain.query.QueryTemplate;

import java.sql.DatabaseMetaData;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

/**
 * Creates {@link Statement} based on the type and parameters of a given query:
 *
 * _CallableStatement for stored p rocedure queries _PreparedStatement for queries with input parameters _Standard Statement
 * otherwise
 */
public class QueryStatementFactory implements ConfigurableStatementFactory {

  private int maxRows;

  /**
   * There is no int value to indicate that the property was not set, so using null to indicate that
   */
  private Integer fetchSize;

  private int queryTimeout = 0;

  @Override
  public Statement create(DbConnection connection, QueryTemplate queryTemplate) throws SQLException {
    return create(connection, queryTemplate, new NoAutoGenerateKeysStrategy());
  }

  @Override
  public Statement create(DbConnection connection, QueryTemplate queryTemplate, AutoGenerateKeysStrategy autoGenerateKeysStrategy)
      throws SQLException {
    Statement result;

    if (queryTemplate.getType().equals(STORE_PROCEDURE_CALL)) {
      DatabaseMetaData metadata = connection.getJdbcConnection().getMetaData();
      int resultSetType;
      // MULE-10854: some drivers need scrolling for fetching CLOBs, but others don't support it so we check
      if (metadata.supportsResultSetType(TYPE_SCROLL_INSENSITIVE)) {
        resultSetType = TYPE_SCROLL_INSENSITIVE;
      } else if (metadata.supportsResultSetType(TYPE_SCROLL_SENSITIVE)) {
        resultSetType = TYPE_SCROLL_SENSITIVE;
      } else {
        resultSetType = TYPE_FORWARD_ONLY;
      }
      result = connection.getJdbcConnection().prepareCall(queryTemplate.getSqlText(), resultSetType, ResultSet.CONCUR_READ_ONLY);
    } else {
      boolean hasInputParams = queryTemplate.getInputParams().size() > 0;

      if (hasInputParams) {
        result = autoGenerateKeysStrategy.prepareStatement(connection, queryTemplate);
      } else {
        result = connection.getJdbcConnection().createStatement();
      }
    }

    if (maxRows > 0) {
      result.setMaxRows(maxRows);
    }

    if (fetchSize != null) {
      result.setFetchSize(fetchSize);
    }

    if (queryTimeout != 0) {
      result.setQueryTimeout(queryTimeout);
    }

    return result;
  }

  @Override
  public void setMaxRows(int max) {
    this.maxRows = max;
  }

  @Override
  public void setFetchSize(int size) {
    this.fetchSize = size;
  }

  @Override
  public void setQueryTimeout(int queryTimeout) {
    checkArgument(queryTimeout >= 0, "Query timeout must be positive");
    this.queryTimeout = queryTimeout;
  }
}
